package com.yunxiangyue.info_user

import android.Manifest
import android.app.DatePickerDialog
import android.content.Intent
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.yunxiangyue.User
import com.yunxiangyue.User_room.UserDao
import com.yunxiangyue.User_room.UserDatabase
import com.yunxiangyue.app.R
import com.yunxiangyue.server.ConnectExample
import de.hdodenhof.circleimageview.CircleImageView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.*
import java.util.*

class UserInfo : AppCompatActivity(),View.OnClickListener {
    val str= arrayOf("男","女")

    lateinit var mlauncher:ActivityResultLauncher<Intent>
    val personId=1

    private var name: TextView? = null
    private var intro: TextView? = null
    private var university: TextView? = null
    private var born: TextView? = null
    private var spinner_gender: Spinner? = null
    private var imagePhoto: ImageView? = null
    private var save_info: TextView? = null
    private var photo: CircleImageView? = null
    private  var imgE:String = ""
    private  var nameE:String = ""
    private  var genderE:String =""
    private  var birthdayE:String=""
    private  var universityE:String=""
    private  var introE:String=""
    private  var userDao: UserDao?=null
    private  var phone:String=""
    private  var pwd:String=""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user_info)
        userDao = UserDatabase.getUserDatabase(this).userDao()

        name = findViewById(R.id.name)
        intro = findViewById(R.id.intro)
        university = findViewById(R.id.university)
        born = findViewById(R.id.born)
        spinner_gender = findViewById(R.id.spinner_gender)
        imagePhoto = findViewById(R.id.photo)
        save_info = findViewById(R.id.save_info)
        phone = intent.getStringExtra("phone").toString()
        Log.d("ning","本页的号码是"+phone)

        //创建该页面时把该用户的信息填入该页面
        val userList = userDao?.queryUserByPhone_list(phone)
        if(userDao?.queryUserByPhone(phone)!!>0){
            for(user in userList!!){
                    name?.setText(user.nike)
                    nameE = user.nike
                    intro?.setText(user.intro)
                   introE = user.intro
                    university?.setText(user.university)
                universityE=user.intro
                    spinner_gender?.tag = user.gender
                Log.d("ning","spinner_gender:${spinner_gender?.tag}")
                    genderE = user.gender
                    born?.setText(user.birthday)
                birthdayE = user.birthday
                Log.d("ning",user.nike+":"+user.intro+":"+user.birthday+":"+user.phone+":"+user.pwd)
            }
        }


//        var ggender=userr.readableDatabase.query(Table, arrayOf("gender"),"id=?", arrayOf(personId.toString()),null,null,null)

//        use.name=name?.text.toString()
//        use.introductory=intro?.text.toString()
//        use.university=university?.text.toString()

        val actionBar=supportActionBar
        if(actionBar!=null){
//            设置ActionBar是否显示返回键
            actionBar.setDisplayHomeAsUpEnabled(true)
//            导入返回键图片
            actionBar.setHomeAsUpIndicator(R.drawable.ic_fanhui_2)
//            设置是否显示标题
            actionBar.setDisplayShowTitleEnabled(true)
            actionBar.setTitle("编辑我的资料")
        }
        name?.setOnClickListener(this)
        born?.setOnClickListener(this)
        intro?.setOnClickListener(this)
        university?.setOnClickListener(this)
        save_info?.setOnClickListener(this)
        photo?.setOnClickListener(this)
        //性别选择器的使用
        spinner_gender?.onItemSelectedListener = object :
        AdapterView.OnItemSelectedListener{
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                val itemContent = parent?.getItemAtPosition(position).toString()
                if(itemContent!=""){
                    genderE = itemContent
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }


//        从相册选择图片后的回调方法   把图片的Uri设置为photo的Uri
        mlauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult(),
            ActivityResultCallback {
                if(it.resultCode== RESULT_OK){
                    val intent=it.data
                    val UriPic=intent?.data
                    if(UriPic!=null){
                        photo?.setImageURI(UriPic)
                    }
                }
            })

        Log.d("innnn","--------------------------------------------------------------")

    }
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            android.R.id.home ->
            {
                //关闭数据库
                finish()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==1){
            if(resultCode==1){
                val u=data?.getStringExtra("name")
                name?.text=u.toString()
                nameE = u.toString()
            }
            if(resultCode==2){
                val u=data?.getStringExtra("university")
                university?.text=u.toString()
                universityE = u.toString()
            }
            if(resultCode==3){
                val u=data?.getStringExtra("intro")
                intro?.text=u.toString()
                introE = u.toString()
            }

        }
        if(requestCode==100){
            try {
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            }

        }
    }


    val updateCallback:(Boolean) -> Unit = {
        if(it){
            Log.d("update","result is success")
        }else{
            Log.d("update","result is failed")
        }
    }

    override fun onClick(p0: View?) {
        when(p0?.id){
            R.id.name -> {
                val intent= Intent(this,rectify_name::class.java)
                startActivityForResult(intent,1)
            }
            R.id.born -> {
                showDatePickerDialog(this@UserInfo, born!!)
            }
            R.id.university -> {
                val intent= Intent(this,university_activity::class.java)
                startActivityForResult(intent,1)
            }
            R.id.intro -> {
                val intent= Intent(this,rectify_intro::class.java)
                startActivityForResult(intent,1)
            }
            R.id.photo-> {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1);
                } else {
                    //访问相册
                    val intent=Intent(Intent.ACTION_GET_CONTENT)
                    intent.setType("image/*")
                    mlauncher.launch(intent)
                }
            }
//            R.id.spinner_gender -> {
//                var i=0
//                var adapter= ArrayAdapter<String>(this, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,str)
//                spinner_gender?.adapter=adapter
//                for(i in 0..1){
//                    if(str.get(i)==spinner_gender?.selectedItem.toString()){
//                        genderE=str.get(i)
//                        break
//                    }
//                }
//
//            }

//            点击保存按钮后更新数据库的语句，只有一句
            R.id.save_info -> {
                //更新该条信息
                //远程数据库修改该用户的信息
                val connectExample:ConnectExample =  ConnectExample()
                //只更新对应的字段   如名字  大学  简介  性别  地区 生日   密码字段保持不变   在前面更换密码的地方再修改
                connectExample.updateUser(phone,"",nameE.toString(), userType = "false",genderE.toString(),birthdayE.toString(), region = "",universityE.toString(),introE.toString(),updateCallback)

                val user = User(nameE,genderE,birthdayE,universityE,introE,pwd)
                user.phone = phone
                CoroutineScope(Dispatchers.IO).launch {
                    if(userDao?.queryUserByPhone(phone = phone.toString())==0){
                        //说明该用户信息还未在表中存入过
                        userDao?.insertUser(user)
                    }else{
                        val updatedRows = userDao?.updateUser(user)
                        if (updatedRows!! > 0) {
                            // 更新成功
                            Log.d("ning","更新成功")
                        } else {
                            // 没有记录被更新，可能是因为phone不存在
                            Log.d("ning","更新失败")
                        }
                    }
                }
                finish()
//                Log.d("ning",user.nike+":"+user.intro+":"+user.birthday+":"+user.phone+":"+user.pwd)
            }

            R.id.profile_picture -> {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1);
                } else {
                    //访问相册
                    InputPicture()
                }
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1) {
            if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                InputPicture()
            } else {
                Toast.makeText(this, "你拒绝打开此权限，无法更换头像！", Toast.LENGTH_SHORT).show()
            }
        }
    }

    // 打开照片文件
    private fun InputPicture() {
        //Intent.ACTION_PICK 从数据中选择一个项目 (item)，将被选中的项目返回。
        //MediaStore.Images.Media.EXTERNAL_CONTENT_URI 获取外部的URI
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        //参数一:对应的数据的URI 参数二:使用该函数表示要查找文件的MIME类型
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        startActivityForResult(intent, 100);
    }

    override fun onStop() {
        super.onStop()
        //保存序列后的对象到文件中
//        关闭数据库连接
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    //显示 日期选择器
    private var calendar = Calendar.getInstance(Locale.CHINA)
    private  val themeResId = 3//0是日历图1是滚轴
    /**
     * 日期选择
     * @param activity
     * @param born
     */
    fun showDatePickerDialog(
        activity: UserInfo,
        born: TextView
    ) {
        calendar = Calendar.getInstance(Locale.CHINA)
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        DatePickerDialog(
            activity, themeResId,
            DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
                // 绑定监听器(How the parent is notified that the date is set.)
                // 此处得到选择的时间，可以进行你想要的操作
                born.text = "$year"+"年"+"${monthOfYear+1}"+"月"+"$dayOfMonth"+"日"
                birthdayE="$year"+"年"+"${monthOfYear + 1}"+"月"+"$dayOfMonth"+"日"

            } // 设置初始日期
            , calendar.get(Calendar.YEAR)
            , calendar.get(Calendar.MONTH)
            , calendar.get(Calendar.DAY_OF_MONTH)).show()
    }


}